package org.example.springmvc_demo4.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.springmvc_demo4.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private final static int validTime = 60 * 1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());

        //设置返回类型
        response.setContentType("image/jpeg");

        //禁止缓存
        response.setHeader("Progma","No-cache");

        String code = lineCaptcha.getCode();
        //图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());

        //将正确验证码存入session中
        session.setAttribute(captchaProperties.getSession().getKey(), code);
        session.setAttribute(captchaProperties.getSession().getDate(), new Date());

        response.getOutputStream().close();
    }

    @RequestMapping("/check")
    public boolean check(String inputCode, HttpSession session){
        if(!StringUtils.hasLength(inputCode)){
            return false;
        }

        String saveCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());

        if(saveCode.equalsIgnoreCase(inputCode)){
            if(saveDate == null || System.currentTimeMillis() - saveDate.getTime() > validTime){
                return false;
            }
            return true;
        }

        return false;
    }


}
